import 'dart:typed_data';

import 'package:aichat_flutter_wallet/module/module_news/model/remark_item.dart';
import 'package:aichat_flutter_wallet/module/module_news/provider/news_provider.dart';
import 'package:aichat_flutter_wallet/module/module_news/utils/news_util.dart';
import 'package:aichat_flutter_wallet/module/module_news/widget/new_commemt_widget.dart';
import 'package:aichat_flutter_wallet/module/module_news/widget/new_detail_remark_h2.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/lib_util.dart';

import '../../../module_common/bridge/native_channel_bridge.dart';

class NewDetailRemarkH1 extends StatefulWidget {
  RemarkItem item;
  String? article_id;
  Function? doCommentSuccess;
  NewDetailRemarkH1({Key? key, required this.item, this.article_id,this.doCommentSuccess})
      : super(key: key);

  @override
  _NewDetailRemarkH1State createState() => _NewDetailRemarkH1State();
}

class _NewDetailRemarkH1State extends State<NewDetailRemarkH1> {
  bool isEnd = false;
  late List<RemarkItem> remarkListArr = widget.item.sub_comment;
  late NewsProvider newsProvider;
  Uint8List? videoImg;
  @override
  void initState() {
    super.initState();
    if (widget.item.sub_comment.length > 3) {
      remarkListArr = widget.item.sub_comment.sublist(0, 3);
    }
    newsProvider = context.read<NewsProvider>();
    if (widget.item.videos.isNotEmpty) {
      getVideoImage(widget.item.videos[0]);
    }
  }

  getVideoImage(String videoUrl) async {
    videoImg = await NewsUtil.getVideoThumb(videoUrl);
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              child: PublicImage(
                image: widget.item.pic,
              ),
              borderRadius: BorderRadius.circular(40),
            ),
            SizedBox(
              width: 8.w,
            ),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  '${NewsUtil.getName(widget.item.user_name)}',
                  style: TextStyle(fontSize: 12.sp, color: AppColors.c_868391),
                ),
                SizedBox(
                  height: 5.w,
                ),
                Text(
                  '${widget.item.content}',
                  style: TextStyle(fontSize: 14.sp, color: AppColors.c_333333),
                ),
                if (widget.item.images.isNotEmpty)
                SizedBox(
                  height: 12.w,
                ),
                if (widget.item.images.isNotEmpty)
                  ClipRRect(
                    borderRadius: BorderRadius.circular(10.w),
                    child: InkWell(
                      splashColor: Colors.transparent,
                      onTap: () {
                        NativeChannelBridge().flPreviewMedia(type: 'image',index: 0.toString(),datas: widget.item.images);
                      },
                      child: PublicImage(
                        image: widget.item.images[0],
                        width: 164.w,
                        height: 164.w,
                      ),
                    ),
                  ),
                if (videoImg != null)
                  newsProvider.getVideoWidget(
                      videoImg: videoImg!,
                      callback: () {
                        NativeChannelBridge().flPreviewMedia(type: 'video',index: 0.toString(),datas: widget.item.videos);
                      }),
                SizedBox(
                  height: 8.w,
                ),
                newsProvider.getRemarkFooter(widget.item, doComment: (res) {
                  NewsUtil.showCommentDialog(
                      ctx: context,
                      toName: widget.item.user_name,
                      success: (CommemtTypeCallBackData value) {
                    print('value1===${value}');
                    doComment(res,
                        content: value.content,
                        videos: value.videos,
                        images: value.images);
                  });
                }, doLike: doLike),
                SizedBox(
                  height: 17.w,
                ),
                ...getSubRemak(list: remarkListArr),
                if (widget.item.sub_comment.length > 3)
                  InkWell(
                    splashColor: Colors.transparent,
                    onTap: () {
                      if (!isEnd) {
                        setState(() {
                          remarkListArr = widget.item.sub_comment;
                          isEnd = true;
                        });
                      } else {
                        print('取消');
                        var list = remarkListArr.sublist(0, 3);
                        remarkListArr = list;
                        isEnd = false;
                        setState(() {});
                      }
                    },
                    child: Row(
                      children: [
                        SizedBox(
                          width: 54.w,
                        ),
                        Container(
                          height: 1.h,
                          width: 20.w,
                          color: AppColors.c_8667FE,
                        ),
                        SizedBox(
                          width: 5.w,
                        ),
                        Text(
                          isEnd
                              ? 'Conceal'
                              : 'ALL(${widget.item.sub_comment.length})',
                          style: TextStyle(
                              fontSize: 12.sp, color: AppColors.c_8667FE),
                        ),
                        SizedBox(
                          width: 3,
                        ),
                        PublicImage(
                          image: isEnd
                              ? 'assets/images/common/news_more.png'
                              : 'assets/images/common/news_more_up.png',
                          width: 15.w,
                          height: 15.w,
                        )
                      ],
                    ),
                  )
              ],
            ))
          ],
        )
      ],
    ));
  }

// 二级评论
  List<Widget> getSubRemak({required List list}) {
    // print('list=================${list}');
    List<Widget> widgetList = [];
    list.asMap().forEach((index, e) {
      widgetList.add(NewDetailRemarkH2(
          articleId: widget.article_id.toString(),
        doCommentSuccess:(){
          if(widget.doCommentSuccess!=null){
            widget.doCommentSuccess!();
          }
        },
        remarkItem: e,
        onchange: (item) {
          remarkListArr.insert(0, item);
          setState(() {});
        },
      ));
    });
    return widgetList;
  }

  // 评论
  doComment(RemarkItem remarkItem,
      {String? content, List<String>? videos, List<String>? images}) {
    newsProvider.doComment(
        images: images ?? [],
        videos: videos ?? [],
        target_type: remarkItem.target_type,
        level: 2,
        target_id: remarkItem.id,
        article_id: widget.article_id,
        content: content ?? '',
        success: (value) {
          print('value--comment===${value}');
          Toast.show(context, message: 'Reply successful');
          if (value!.code == 0) {
            RemarkItem valueItem = RemarkItem.fromJson(value.data['comment']);
            widget.item.sub_comment.insert(0, valueItem);
            remarkItem.comment_count += 1;
            if(widget.doCommentSuccess!=null){
              widget.doCommentSuccess!();
            }
            NativeChannelBridge().flGoCommentSuccess(remarkItem.target_type.toString(),widget.article_id.toString(),'comment');
            setState(() {});
          }
        },
        fail: () {
          Toast.show(context,
              message: 'Network error, sending failure', status: '2');
        });
  }

  // 点赞，取消点赞
  doLike(RemarkItem remarkItem) {
    newsProvider.doLike(
        target_id: remarkItem.id,
        target_type: 0,
        like_status: remarkItem.like_status,
        beforeCall: (value) {
          if (value) {
            remarkItem.like_count -= 1;
            remarkItem.like_status = 1;
          } else {
            remarkItem.like_count += 1;
            remarkItem.like_status = 0;
          }
          setState(() {});
        },
        failCall: (value) {
          if (value) {
            remarkItem.like_count += 1;
            remarkItem.like_status = 0;
          } else {
            remarkItem.like_count -= 1;
            remarkItem.like_status = 1;
          }
          setState(() {});
        });
  }
}
